<?php
header("Content-Type: text/html; charset=iso-8859-1");
require_once('include/db_connection.php');
require_once('include/script_includes.php');

if(isset($_GET['request'])) {
	$request = $_GET['request'];
}

if ($request == 'gameSaveShow') {
	if(isset($_GET['playerid'])) {
		game_save($mysqli,$_GET['game_id'], $_GET['role'], $_GET['playerid'],null,$_GET['manr']);
	} else{
		game_save($mysqli,$_GET['game_id'], $_GET['role'], null,null,$_GET['manr']);
	}
	mysqli_close($mysqli);
	exit;
}

if ($request == 'gamesTableShow') {
	$yearkw = date('Y') . date('W');
	games_table($mysqli, $yearkw,null,null,$_GET['manr']);
	mysqli_close($mysqli);
	exit;
}

if ($request == 'gamesKWSummaryShow') {
	$yearkw = date('Y') . ltrim( date('W'),'0');
        if ($yearkw != "all") {
            games_kw_summary($mysqli, $yearkwselected, $yearkwselected);
        } else{
            games_summary($mysqli);
        }
	mysqli_close($mysqli);
	exit;
}

if ($request == 'randomGameShowByGameID') {
	$rndGame = getRandomGame($mysqli,$_GET['role'],$_GET['game_id']);	
	mysqli_close($mysqli);	
	exit;
}
if ($request == 'randomGameShow') {
	$rndGame = getRandomGame($mysqli,$_GET['role'],null);		
	mysqli_close($mysqli);
	exit;
}

if ($request == 'gameSave') {
	$res = $mysqli->query("select max(id) max_game_id from game_data");
	$row = $res->fetch_assoc();
	$id = $row['max_game_id'] + 1;
	if(isset($_GET['game_uuid'])) {
		$gameUUID = $_GET['game_uuid'];
	} else {
		$gameUUID = 0;
	}
	foreach ($_GET as $key => $value) {
		if (startsWith($key, 'player_') && $value != "") {
			$player_id = explode("_", $key)[1];
			$sql = "INSERT INTO game_data (id,date, game_id, game_uuid, player_id, score,manr) VALUES (" . $id . ",CURDATE(), " . $_GET['game_id'] . "," . $gameUUID . "," . $player_id . "," . $value . "," . $_GET['manr'] . ")";
			mysqli_query($mysqli, $sql);
			$mysqli->commit();
		}
	}
	//$rndGame = rand(1, 20);
	game_save($mysqli,$_GET['game_id'], $_GET['role'], $_GET['playerid'],null,$_GET['manr']);
	mysqli_close($mysqli);
	exit;
}    
if ($request == 'deleteGame') {
        $sql = "DELETE FROM game_data where id = ".$_GET['id'];
	mysqli_query($mysqli, $sql);
	$mysqli->commit();
	
	$yearkw = date('Y') . date('W');
	games_table($mysqli, $yearkw,null,null,$_GET['manr']);
	mysqli_close($mysqli);
	exit;
}
if ($request == 'livelink') {
	$user_id = $_GET['user_id'];
	$manr = $_GET['manr'];
	$sql = "SELECT * FROM `game_score_v2` where manr = ". $manr ." order by id desc limit 1";
	$lastScoreDate = new DateTime($mysqli->query($sql)->fetch_object()->creation_date);
	$now = new DateTime();
	$now->sub(date_interval_create_from_date_string('2 minutes')); 
	if ($lastScoreDate > $now) {
		$sql = "SELECT firstName,game_id FROM game_score_v2, (select max(game_uuid) game_uuid from game_score_v2 where manr = ". $manr .") tmp,players WHERE players.manr = ". $manr ." and game_score_v2.game_uuid = tmp.game_uuid
				and players.id = game_score_v2.player_id
				group by player_id";
		$players = array();
		$gameID = "";
		$res = $mysqli->query($sql);
		while (($row = $res->fetch_assoc()) != false) {
			array_push($players,$row['firstName']);
			$gameID = $row['game_id'];
		}
		if ($gameID != null) {
			$sql = "select gameGroup,name from games_v2 where id = ".$gameID;
			$gameGroup = $mysqli->query($sql)->fetch_object()->gameGroup;
			$gameName = $mysqli->query($sql)->fetch_object()->name;
			echo "<a href='#' class='blink red' onClick='javascipt:window.open(\"dartautomat.php?request=livedartscoreboard&user_id=".$user_id."&manr=".$manr."\",\"Live View Scoreboard\", \"width=1300, height=800, location=no, menubar=no, scrollbars=no, status=no, toolbar=no\")'>Spiel l&auml;uft...".$gameGroup." ".$gameName." (".join(",", $players).")</a>";
			echo "<script type='text/javascript'>titleMarquee('Spiel...l&auml;uft...');</script>";
		}
	} else {
		echo "<script type='text/javascript'>document.title = 'MMS-Dart-Liga';window.clearTimeout(timer);</script>";
	}
	if (isset($user_id) && $user_id != null) {
		$sql = "update players set heartbeat=NOW() where id=".$user_id;
		mysqli_query($mysqli, $sql);
		$mysqli->commit();
	}

	exit;
}
?>